package com.vvlive.caibao.smartcity.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.vvlive.caibao.smartcity.app.SmartCityApp;
import com.vvlive.caibao.smartcity.base.BaseActivity;
import com.vvlive.caibao.smartcity.base.GetMeetingsInterface;
import com.vvlive.caibao.smartcity.base.ListHttpCallBack;
import com.vvlive.caibao.smartcity.base.MeetingsListInterface;
import com.vvlive.caibao.smartcity.bean.MeetingByMonth;
import com.vvlive.caibao.smartcity.fragment.FriendsFragment;
import com.vvlive.caibao.smartcity.fragment.IndexFragment;
import com.vvlive.caibao.smartcity.fragment.MeetingFragment;
import com.vvlive.caibao.smartcity.utils.MeetingsController;
import com.vvlive.caibao.smartcity.view.CommonActionBar;
import com.vvlive.caibao.smartcity.view.CommonActionBar.OnMoreListener;

import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import smartcity.vvlive.caibao.com.smartc.R;

/**
 * Created by lenovo on 2015/6/26.
 */
public class IndexFragmentActivity extends BaseActivity
        implements OnCheckedChangeListener, OnMoreListener, MeetingsListInterface {

    private final static int TAG_SETTINGS = 0;
    private final static int TAG_PUBLISH = 1;

    private RadioGroup mIndexGroup;
    private RadioButton mIndex, mLife, mFind;
    private FragmentManager mFragmentManager;
    private FragmentTransaction mFragmentTransaction;

    private CommonActionBar actionBar;

    //用来设置主页indexfragment
    private IndexFragment ift = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.index_fragment);
        mIndexGroup = (RadioGroup) findViewById(R.id.index_buttom);
        mIndexGroup.setOnCheckedChangeListener(this);
        mIndex = (RadioButton) findViewById(R.id.index);
        mLife = (RadioButton) findViewById(R.id.life);
        mFind = (RadioButton) findViewById(R.id.find);
        if (savedInstanceState == null) {
            mFragmentManager = getSupportFragmentManager();
            mFragmentTransaction = mFragmentManager.beginTransaction();
            IndexFragment indexActivity = new IndexFragment();
            ift = indexActivity;
            mFragmentTransaction.add(R.id.index_conter, indexActivity, "Index");
            mFragmentTransaction.commit();
        }

    }

    /**
     *
     * */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // 登录状态下，不能切换各个板块
        if(SmartCityApp.currentUser == null){
            if(checkedId > 0) {
                toast("请先登录！");
            }
            mIndex.setChecked(true);
            return;
        }
        FragmentTransaction ftt = mFragmentManager.beginTransaction();
        Fragment index_fm = mFragmentManager.findFragmentByTag("Index");
        Fragment life_fm = mFragmentManager.findFragmentByTag("Friend");
        Fragment find_fm = mFragmentManager.findFragmentByTag("Find");
        if (index_fm != null) {
            ftt.hide(index_fm);
        }
        if (life_fm != null) {
            ftt.hide(life_fm);
        }
        if (find_fm != null) {
            ftt.hide(find_fm);
        }
        switch (checkedId) {
            case R.id.index:
                if (index_fm != null) {
                    ftt.show(index_fm);
                } else {
                    IndexFragment indexActivity = new IndexFragment();
                    ftt.add(R.id.index_conter, indexActivity, "Index");
                }
                actionBar.setTitle("首页");
                break;
            case R.id.life:
                if (life_fm != null) {
                    ftt.show(life_fm);
                } else {
                    FriendsFragment friendsFragment = new FriendsFragment();
                    ftt.add(R.id.index_conter, friendsFragment, "Friend");
                }
                actionBar.setTitle("生活");
                actionBar.setMoreVisible(false);
                break;
            case R.id.find:

                if (find_fm != null) {
                    ftt.show(find_fm);
                } else {
                    MeetingFragment meetingFragment = new MeetingFragment();
                    ftt.add(R.id.index_conter, meetingFragment, "Find");

                }
                actionBar.setTitle("会议");
                actionBar.setMoreVisible(false);
                actionBar.setMoreIcon(R.mipmap.more);
                actionBar.getMoreView().setTag(TAG_PUBLISH);
                break;
            default:
                break;
        }
        ftt.commit();
    }


    @Override
    protected int getContentViewRes() {
        return R.layout.index_fragment;
    }

    @Override
    public void initWidget() {
        actionBar = getCommonActionBar();
        actionBar.setBackVisible(false);
        actionBar.setTitle("首页");
        actionBar.setMoreIcon(R.mipmap.leimu);
        actionBar.getMoreView().setTag(TAG_SETTINGS);
        actionBar.setOnMoreListener(new IndexMoreListener());
        actionBar.setMoreVisible(false);
    }

    /*
     * 会议信息控制
     * 163-334
     */
    private List<MeetingByMonth> mMeetingBeans;
    private MeetingsController mController;
    private boolean isRequesting = false;
    private Calendar mCalendar = Calendar.getInstance();

    @Override
    public List<MeetingByMonth> getMeetingsList() {
        return mMeetingBeans;
    }

    @Override
    public void setMeetingsList(List<MeetingByMonth> meetingsList) {
        this.mMeetingBeans = meetingsList;
    }

    @Override
    public MeetingsController getMeetingsController() {
        if (mController == null) {
            mController = new MeetingsController();
        }
        return mController;
    }

    @Override
    public void setOnMeetingsPreparedListener(final OnMeetingsPreparedListener onMeetingsPreparedListener,
                                              Calendar calendar, int tag) {
        if (onMeetingsPreparedListener != null) {
            if (getMeetingsList() != null) {
                if (isTheSameDay(mCalendar, calendar)) {
                    onMeetingsPreparedListener.onGetMeetings(mMeetingBeans);
                    isRequesting = false;
                } else {
                    mCalendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
                    startRequesting(onMeetingsPreparedListener, calendar);
                    isRequesting = true;
                }
            } else {
                if (!isRequesting) {
                    startRequesting(onMeetingsPreparedListener, calendar);
                } else {
                    new MeetingsTimer(onMeetingsPreparedListener) {
                        @Override
                        public void onTimeOver() {
                            // 时间到
                        }
                    }.check();
                }
            }
        }
    }

    /**
     * 开始请求
     *
     * @param onMeetingsPreparedListener
     * @param calendar
     */
    private void startRequesting(OnMeetingsPreparedListener onMeetingsPreparedListener,
                                 Calendar calendar) {
        isRequesting = true;
        getMeetingsController().fetchMeetingsByMonth(calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1, new MeetingGetCallBack(onMeetingsPreparedListener));
    }

    /**
     * 两个日期是否是同一天
     *
     * @param c1
     * @param c2
     * @return
     */
    private boolean isTheSameDay(Calendar c1, Calendar c2) {
        return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)
                       && c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH);
    }

    /*
     * If the meetings list is null, and at the same time,
     * meetings are being requested, then we don't need to
     * request one more time, instead, checking if the meetings
     * is null over and over again, also if the request is done.
     */
    private abstract class MeetingsTimer extends Timer {

        private static final int WHAT = 101;
        private static final int DELAY = 100;
        private static final int PERIOD = 100;

        private static final int MAX_COUNT = 30;
        private int max = MAX_COUNT;

        private int mCount = 0;

        private TimerTask mTask = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(WHAT);
            }
        };

        private Handler mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                if (msg.what == WHAT) {
                    if (getMeetingsList() != null) {
                        if (MeetingsTimer.this.onMeetingsPreparedListener != null) {
                            MeetingsTimer.this.onMeetingsPreparedListener.onGetMeetings(mMeetingBeans);
                            isRequesting = false;
                            MeetingsTimer.this.cancel();
                        }
                    } else {
                        if (mCount > max) {
                            isRequesting = false;
                            MeetingsTimer.this.cancel();
                            onTimeOver();
                        } else {
                            mCount++;
                        }

                    }
                }
            }
        };

        private OnMeetingsPreparedListener onMeetingsPreparedListener;

        public MeetingsTimer(OnMeetingsPreparedListener onMeetingsPreparedListener) {
            this.onMeetingsPreparedListener = onMeetingsPreparedListener;
        }

        public MeetingsTimer(int max, OnMeetingsPreparedListener onMeetingsPreparedListener) {
            this.max = max;
            this.onMeetingsPreparedListener = onMeetingsPreparedListener;
        }

        public void check() {
            this.schedule(mTask, DELAY, PERIOD);
        }

        public abstract void onTimeOver();
    }

    @Override
    public void refreshMeetings(OnMeetingsRefreshListener onMeetingsRefreshListener) {
        if (onMeetingsRefreshListener != null) {
            getMeetingsController().fetchMyMeetings(new MeetingGetCallBack(onMeetingsRefreshListener));
        }
    }

    private final class MeetingGetCallBack extends ListHttpCallBack<MeetingByMonth> {

        private GetMeetingsInterface meetingsInterface;

        public MeetingGetCallBack(GetMeetingsInterface meetingsInterface) {
            this.meetingsInterface = meetingsInterface;
        }

        @Override
        public void onSuccess(List<MeetingByMonth> list) {
            setMeetingsList(list);
            meetingsInterface.onGetMeetings(list);
        }

        @Override
        public void onError(int errCode, String str) {
            if (meetingsInterface instanceof OnMeetingsRefreshListener) {
                ((OnMeetingsRefreshListener) meetingsInterface).onFailure(errCode, str);
            }
        }
    }

    private final class IndexMoreListener implements OnMoreListener {

        private Intent mIntent;

        @Override
        public void onMore(View v) {
            int tag = (int) v.getTag();
            switch (tag) {
                case TAG_SETTINGS:
                    if (SmartCityApp.isLogin) {
                        newActivity(SignInActivity.class);
                    } else {
                        toast("请先登录！");
                        newActivity(SignInActivity.class);
                    }
                    break;
                case TAG_PUBLISH:
                    startActivityForResult(getIntent(OrderOneMeetingActivity.class), 400);
                    break;
            }
        }

        private Intent getIntent(Class target) {
            if (mIntent == null) {
                mIntent = new Intent();
            }
            mIntent.setClass(IndexFragmentActivity.this, target);
            return mIntent;
        }
    }

    @Override
    public void onMore(View v) {
        // 发布活动
        startActivity(new Intent(this, PublishOneEventActivity.class));
    }

    private long millis = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //
            boolean is;
            if (ift != null) {
                is = ift.onBackPressed();
                if (!is) {
                    //双击退出
                    if (System.currentTimeMillis() - millis < 1000) {
                        return super.onKeyDown(keyCode, event);
                    } else {
                        Toast.makeText(this, R.string.click_again_to_exit, Toast.LENGTH_SHORT).show();
                        millis = System.currentTimeMillis();
                        return false;
                    }
                }
            }

        }
        return false;
    }

    static class KeyUtils {

        private static long millis;

        public static boolean tapTwiceToExit(int keyCode, Activity activity) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (System.currentTimeMillis() - millis < 1000) {
                    return true;
                } else {
                    Toast.makeText(activity, R.string.click_again_to_exit, Toast.LENGTH_SHORT).show();
                    millis = System.currentTimeMillis();
                    return false;
                }
            }
            return false;
        }
    }
}
